import React, {Component} from 'react'
import {Tooltip, Input, Tag, Icon} from 'antd'
import propTypes from 'prop-types'
class TagEdit extends Component {
  state = {
    visible: false,
    tags: [],
    inputValue: ''
  }
  handleChange = e => {
    this.setState({
      inputValue: e.target.value
    })
  }
  addTag = e => {
    const {inputValue: currentInput} = this.state
    if (!currentInput) {
      return this.toggleTagInput()
    }
    const tags = this.getCurrentValue()
    tags.push(currentInput)
    this.setState({inputValue: ''})
    this.toggleTagInput()
    this.backValue(tags)
  }
  toggleTagInput = () => {
    const show = !this.state.visible
    this.setState({visible: show}, () => {
      this.input && this.input.focus && this.input.focus()
    })
  }
  handleClose = index => {
    const tags = this.getCurrentValue()
    tags.splice(index, 1)
    this.backValue(tags)
  }
  reset = () => {
    const {defaultValue, value} = this.props
    this.setState({tags: value ? value.slice(0) : defaultValue.slice(0)})
  }
  backValue = (value) => {
    const {onChange} = this.props
    this.setState({tags: value})
    onChange(value)
  }
  getCurrentValue = () => {
    const {value, defaultValue} = this.props
    const {tags} = this.state
    return (value ? value.slice(0) : null) || (tags.length ? tags : null) || defaultValue || []
  }

  componentWillMount() {
    this.reset()
  }

  render() {
    const {visible, inputValue} = this.state
    const {disabled} = this.props
    const tags = this.getCurrentValue()

    return (
      <div>
        {
          tags.map((tag, index) => {
            const isLongTag = tag.length > 20
            const tagElem = (
              <Tag key={index} closable={!disabled} onClose={() => this.handleClose(index)}>
                {isLongTag ? `${tag.slice(0, 20)}...` : tag}
              </Tag>
            )
            return isLongTag ? (
              <Tooltip title={tag} key={index}>
                {tagElem}
              </Tooltip>
            ) : (
              tagElem
            )
          })
        }
        {
          visible && !disabled && (
            <Input
              type="text"
              size="small"
              style={{ width: 78 }}
              onBlur={this.addTag}
              value={inputValue}
              onChange={this.handleChange}
              onPressEnter={this.addTag}
              ref={e => this.input = e}
            />
          )
        }
        {
          !visible && !disabled && (
            <Tag onClick={this.toggleTagInput} style={{ background: '#fff', borderStyle: 'dashed' }}>
              <Icon type="plus" /> 添加
            </Tag>
          )
        }
      </div>
    )
  }
}

TagEdit.propTypes = {
  defaultValue: propTypes.array,
  value: propTypes.array,
  disabled: propTypes.bool,
  onChange: propTypes.func
}
TagEdit.defaultProps = {
  disabled: false,
  onChange: () => {}
}

export {TagEdit}
